package longfly.development;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;


import longfly.development.POS_Setup.insert_Thread;
import longfly.development.Service_Test.MyBinder;

import casio.serial.SerialPort;
import android.app.Activity;
import android.app.ProgressDialog;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class Service_manage extends Activity {
    /** Called when the activity is first created. */

	TextView	TEST;
	Button		TEST_BTN;
	Button		TEST_EXIT;
	Button		TEST_SAVE;
	Button		BUTTON_1;
	Button		BUTTON_2;
	Button		BUTTON_3;
	Button		BUTTON_4;
	Button		BUTTON_5;
	Button		BUTTON_6;
	Spinner		PRT_BTL;
	Spinner		PRT_DUANKOU;

	private SerialPort mSerialPort = null;		//串口设备描述
	protected OutputStream mOutputStream;		//串口输出描述
	ProgressDialog progressDialog;
	SQLiteDatabase db;
	
	  
    int	   TTY_BPS = 0;			//串口的初始信息！只在安装后第一次有用！以后会从xml中读出配置信息
	String TTY_DEV = null;
	int		prt_btl,prt_duankou;	
    private ArrayAdapter adapter_prt_btl;  
    private ArrayAdapter adapter_prt_duankou;  
    
    Intent intent = new Intent();
//    Intent intent = new Intent(this, Service_Test.class);
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
       find_id();
       key_things();
       init_view();

		db = SQLiteDatabase.openOrCreateDatabase(this.getFilesDir().toString()+"/Android_POS.db3", null);

       intent.setAction("longfly.development.Service_Test");
       TEST_BTN.setText("启动Service");
       TEST_SAVE.setText("关闭Service");

       BUTTON_2.setText("绑定Service");
       BUTTON_4.setText("解除Service");
       BUTTON_6.setText("监听Service");

       BUTTON_5.setText("打开新窗口");

	}

	
	Service_Test.MyBinder binder;
	
	//定义一个ServiceConnection对象
	private	ServiceConnection conn = new ServiceConnection(){

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			System.out.println("Service  is connnected");
			//获取Service的onbind方法所返回的的binder对象
			binder = (Service_Test.MyBinder) service;
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			System.out.println("Service  is Disconnnected");			
		}
	};
	
	private void key_things() {
		// TODO Auto-generated method stub
		TEST_BTN.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{				   						
		   		//1.传统方式
		   		startService(intent);
		   		//2.绑定方式
		   	}
	    });	

		TEST_SAVE.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{	
		   		//1.传统方式
		   		stopService(intent);
		   		//2.绑定方式
		   	}
	    });	

		BUTTON_1.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{	
		   		//绑定Service
				read_tcp.start();

		   	}
	    });	
		
		BUTTON_2.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{	
		   		//2.绑定方式
		   		bindService(intent, conn, Service.BIND_AUTO_CREATE);  		
		   	}
	    });	
		BUTTON_3.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{	
		   		//绑定Service
		   		
		   	}
	    });			
		BUTTON_4.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{	
		   		//2.绑定方式
		   		try {
			   		unbindService(conn);					
				} catch (Exception e) {
					// TODO: handle exception
				}
		   	}
	    });			
		BUTTON_5.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{	
		   		//绑定Service
	    		Intent intent_page_new = new Intent();
    			intent_page_new.setClass(Service_manage.this, POS_System.class);
	    		startActivity(intent_page_new);	
				overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
		   	}
	    });			
		BUTTON_6.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{	
		   		int ii = binder.getCount();
		   		//2.绑定方式
		   		Toast.makeText(
		   				Service_manage.this,
		   				"Service的count值为："+ ii,
		   				500)
		   			.show();
		   	}
	    });			
		
		TEST_EXIT.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{	
		   		finish();
		   	}
	    });	
		
		PRT_BTL.setOnItemSelectedListener(new OnItemSelectedListener()
		{
            @Override
            public void onItemSelected(AdapterView<?> parent, View arg1,
                int postion, long id) 
            {
            	prt_btl = postion;
            	int pBTL = 0;
            	switch (prt_btl) {
				case 0:
					pBTL = 9600;
					break;
				case 1:
					pBTL = 14400;
					break;
				case 2:
					pBTL = 19200;
					break;
				case 3:
					pBTL = 115200;
					break;					
				case 4:
					pBTL = 256000;
					break;					
				default:
					pBTL = 9600;
					break;
				}
            	TTY_BPS = pBTL;
            	TEST.setText("你选择的波特率是"+ pBTL);
            }

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
			}
         });
		
		PRT_DUANKOU.setOnItemSelectedListener(new OnItemSelectedListener()
		{
            @Override
            public void onItemSelected(AdapterView<?> parent, View arg1,
                int postion, long id) 
            {
            	prt_duankou = postion;
            	String pDKH = null;
            	switch (prt_duankou) {
				case 0:
					pDKH = "/dev/ttymxc0";
					break;
            	case 1:
					pDKH = "/dev/ttymxc1";
					break;
				case 2:
					pDKH = "/dev/ttymxc2";
					break;
				case 3:
					pDKH = "/dev/ttymxc3";
					break;
				case 4:
					pDKH = "/dev/ttymxc4";
					break;					
				case 5:
					pDKH = "/dev/ttymxc5";
					break;					
				case 6:
					pDKH = "/dev/ttymxc6";
					break;	
				case 7:
					pDKH = "/dev/ttymxc7";
					break;									
				default:
					pDKH = "/dev/ttymxc1";
					break;
				}
            	TTY_DEV = pDKH;
            	TEST.setText("你选择的端口号是"+ pDKH);
            }

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
			}
         });		
	}


	private void init_view() {
		// TODO Auto-generated method stub
        //将可选内容与ArrayAdapter连接起来   
		adapter_prt_btl= ArrayAdapter.createFromResource(this, R.array.botelv, android.R.layout.simple_spinner_item); 
 	    //设置下拉列表的风格   
		adapter_prt_btl.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);    
        //将adapter2 添加到spinner中  
		PRT_BTL.setAdapter(adapter_prt_btl);    

/**********************************************************************************/		        
		adapter_prt_duankou= ArrayAdapter.createFromResource(this, R.array.duankou, android.R.layout.simple_spinner_item); 
		adapter_prt_duankou.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);    
		PRT_DUANKOU.setAdapter(adapter_prt_duankou);    
	}
	
	private void find_id() {
		// TODO Auto-generated method stub
		TEST		=	(TextView) findViewById(R.id.about_test);
		TEST_BTN	=	(Button) findViewById(R.id.about_btn_test);
		TEST_SAVE	=	(Button) findViewById(R.id.other_setup_save);
		TEST_EXIT	=	(Button) findViewById(R.id.other_setup_exit);
		BUTTON_1	=	(Button) findViewById(R.id.other_setup_button_1);
		BUTTON_2	=	(Button) findViewById(R.id.other_setup_button_2);
		BUTTON_3	=	(Button) findViewById(R.id.other_setup_button_3);
		BUTTON_4	=	(Button) findViewById(R.id.other_setup_button_4);
		BUTTON_5	=	(Button) findViewById(R.id.other_setup_button_5);
		BUTTON_6	=	(Button) findViewById(R.id.other_setup_button_6);
		
		PRT_BTL		=	(Spinner) findViewById(R.id.customer_spinner_1);
		PRT_DUANKOU	=	(Spinner) findViewById(R.id.customer_spinner_2);
	}
	
	//我的打印机打印字符串的方法！！第一个参数是命令字！倍高倍宽之类！第二个参数是要打印的字符串！
	protected void print_String(byte[] prt_code_buffer, String in_String) {
		// TODO Auto-generated method stub
		int i;
		CharSequence t =  (CharSequence)in_String;
		char[] text = new char[t.length()];	//声明一个和所输入字符串同样长度的字符数组
		for (i=0; i<t.length(); i++) {
			text[i] = t.charAt(i);		//把CharSequence中的charAt传入刚声明的字符数组中
		}
		try {
			byte[] buffer = prt_code_buffer;//倍高倍宽;
			mOutputStream.write(buffer);
			mOutputStream.write(new String(text).getBytes("gb2312"));	//把字符数组变成byte型发送
		} catch (IOException e) {
			e.printStackTrace();
		}		
	}

	protected void Start_Print_Test() {
		// TODO Auto-generated method stub
		progressDialog("正在保存设置 ", "请稍等......");		
     	insert_Thread thread= new insert_Thread();
     	thread.start();		
	}	
	
	/***************     以下是一个带进度条的对话框    **************************************/
	private void progressDialog(String title, String message) {
		// TODO Auto-generated method stub
	     progressDialog = new ProgressDialog(Service_manage.this);
	     progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
	     progressDialog.setMessage(message);
	     progressDialog.setTitle(title);
	     progressDialog.setProgress(0);
	     progressDialog.setMax(100);
	     progressDialog.setCancelable(false);
	     progressDialog.show();
	}

	//用来查询进度条的值！大于100就把进度条Cancel掉
    Handler handler = new Handler(){
    	  @Override
    	  public void handleMessage(Message msg) {
    		  // TODO Auto-generated method stub
    		  if(msg.what>=100){
    			  progressDialog.cancel();
    	       }
    		  progressDialog.setProgress(msg.what);
    		  super.handleMessage(msg);
    	  }
    };

	
//创建一个进程！用来后台加载数据
    class insert_Thread extends Thread{
        public void run(){
	   		byte[] cancel_to_normal = {0x0a, 0x1b, 0x21,0x00};//取消倍高倍宽
	   		byte[] double_h_double_w = { 0x0a, 0x1b, 0x21, 0x30 };//倍高倍宽;

	   		for(int i = 0 ;i<=2;i++)
	   		{
		   		print_String(cancel_to_normal,"===============================");			   		
		   		print_String(double_h_double_w,"第"+i+"行！");			   		
				print_String(cancel_to_normal,"广东韶关龙飞数码科技有限公司");
				print_String(cancel_to_normal,"   Android系统智能收银终端    ");
				print_String(cancel_to_normal,"     欢迎光临“8090自助餐厅”");
				print_String(cancel_to_normal,"12345 abcde ABCDE !@#$% 00");
				print_String(cancel_to_normal,"===============================");
        	
				handler.sendEmptyMessage(i);	//进度条进度	   			
	   		}

//	        finish();
        }
    };
	
	/***************     以上是一个进度条    **************************************/  

    
    /****************    以下是控制网络的线程  ******************************/
	MyThread read_tcp = new MyThread();		//接收PC端数据的线程

	//接收PC端数据的线程
	class MyThread extends Thread 
	{  

		public void run() 
		{
			try {
				control_wifi();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}	
	}
	
	private void control_wifi() throws IOException
	{
		System.out.println("net is wait");
		boolean	net_code = true;	//判断这一条数据是不是命令字
		int	net_code_switch = 0;
		// 创建一个ServerSocket，用于监听客户端Socket的连接请求
		ServerSocket ss = new ServerSocket(30000);
		// 采用循环不断接受来自客户端的请求
		while (true)
		{
			System.out.println("net is ready");
			// 每当接受到客户端Socket的请求，服务器端也对应产生一个Socket
			Socket s = ss.accept();
			System.out.println("net is accept");
			
 			// 将Socket对应的输出流包装成PrintStream
			PrintStream ps = new PrintStream(s.getOutputStream());
/*			
			  // 进行普通IO操作
			ps.println("On or Off");
*/
			//接收
			BufferedReader br = new BufferedReader(
					new InputStreamReader(s.getInputStream()));
					// 进行普通IO操作
			String line = br.readLine();
			//line是获取到的有效数据，它可能是   "命令字" 也可能是 "数据"  
			//由命令字决定接下来的数据是发打印还是发数据库还是控制其他什么部分
			System.out.println(line);
			
			if(net_code == true)
			{
				net_code_switch	= 0;

				if (line.equals("pppp")) 	//如果收到的字符串是pppp 
				{
					net_code_switch = 1;	//命令方式是发厨房打印
				} 
//				if (line.equals("qqqq_get_table_state")) 	//如果收到的字符串是qqqq 
				if (line.equals("qqqq")) 	//如果收到的字符串是qqqq 
				{
					net_code_switch = 2;	//命令方式是发数据库
				} 

				net_code = false;
			}	
			else
			{
				switch (net_code_switch) {
				case 1:
					
					String TTY_DEV = "/dev/ttymxc2";
					try {
						mSerialPort = new SerialPort(new File(TTY_DEV), 9600, 0);
					} catch (SecurityException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}					
					mOutputStream = mSerialPort.getOutputStream();
					
					byte[] cancel_to_normal = {0x0a, 0x1b, 0x21, 0x00};//取消倍高倍宽
					print_String(cancel_to_normal,line);	//交给打印机打印	
					
					break;
				case 2:
					try {
			    		Cursor  cursor = db.rawQuery("select iTableState from lfcy_base_tableinf ", null);
			    		String  fuffer = "0" ;
			    		while (cursor.moveToNext()) {
				    		String state = cursor.getString(cursor.getColumnIndex("iTableState"))+";";			    			
							System.out.println("qqqq successful "+ "   "+state);
							
							fuffer = fuffer + state;
			    		};
						System.out.println("qqqq end =  "+ "   "+fuffer);
						ps = new PrintStream(s.getOutputStream());
						// 进行普通IO操作
						ps.println(fuffer);
					} catch (Exception e) {
						// TODO: handle exception
						System.out.println("qqqq failed");
					}
					break;
				default:
					break;
				}
				
				net_code = true;
			}
			
			
			// 关闭输出流，关闭Socket
			br.close();
			ps.close();
			s.close();
		}
	}
    /****************    以上是控制网络的线程  ******************************/

}